package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/app/model"
	"FeedXmh/hub"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

var Hzfgw_replace = hzfgw_replace{}

type hzfgw_replace struct {
}

func (a *hzfgw_replace) GetPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	id := gconv.String(params["id"])
	old_addr := gconv.String(params["old_addr"])
	new_addr := gconv.String(params["new_addr"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if old_addr != "" {
		where += fmt.Sprintf(" and old_addr='%s'", old_addr)
	}
	if new_addr != "" {
		where += fmt.Sprintf(" and new_addr='%s'", new_addr)
	}
	if farmid != "" {
		where += fmt.Sprintf(" and farmid=%s ", farmid)
	}
	if houseid != "" {
		where += fmt.Sprintf(" and houseid=%s ", houseid)
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("v_hzfgw_replace")
		count, err := model.Where(where).Count()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			res["count"] = count
			start := limit*page - limit
			if start < 0 {
				start = 0
			}
			if order != "" {
				model = model.Order(order)
			} else {
				model = model.Order(" id desc ")
			}
			records, error := model.Limit(start, limit).All()
			if error != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := records.List()
				res["code"] = 0
				res["data"] = list
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *hzfgw_replace) Post(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	params := r.GetFormMap()
	old_addr := gconv.String(params["old_addr"])
	new_addr := gconv.String(params["new_addr"])
	reason := gconv.String(params["reason"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		devices, err := dao.T_device.GetList(fmt.Sprintf(" device_addr='%s' ", old_addr))
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			if len(devices) == 0 {
				res["code"] = -1
				res["msg"] = "错误的原终端SN，系统未找到相关信息，请确认是否填写正确"
			} else {
				//判断新终端是否在线
				clients_data, _ := hub.GetApiClients(gdb.Map{
					"_page":          1,
					"_limit":         100000,
					"_like_clientid": fmt.Sprintf("cid_%s_", model.GW_MODE),
				})
				online, _ := hub.CheckClientsOnline(clients_data, new_addr)
				if !online {
					res["code"] = -2
					res["msg"] = "新终端不在线，请确认新终端SN是否填写正确以及网络是否正常"
				} else {
					//获取备份的终端参数
					paras, err := dao.T_hzfgw_para.GetList(fmt.Sprintf(" addr='%s' ", old_addr))
					if err != nil {
						res["code"] = -3
						res["msg"] = err.Error()
					} else {
						if len(paras) == 0 {
							res["code"] = -4
							res["msg"] = "未找到原终端参数，请确认是否填写正确"
						} else {
							para_str := gconv.String(paras[0]["data"])
							isok, err := hub.SetGwParam(new_addr, para_str)
							if err != nil {
								res["code"] = -5
								res["msg"] = err.Error()
							} else {
								if isok {

									//设置绑定和设置额外参数到新网关
									devices, _ := dao.T_device.GetList(fmt.Sprintf(" device_addr='%s' ", old_addr))
									if len(devices) > 0 {
										d := devices[0]
										d["device_addr"] = new_addr
										dao.T_device.Save(d)
									}
									item := gdb.Map{
										"old_addr":    old_addr,
										"new_addr":    new_addr,
										"reason":      reason,
										"create_user": userid,
										"create_date": gtime.Now().String(),
									}
									_, db_err := dao.T_hzfgw_replace.Save(item)
									if db_err != nil {
										res["code"] = -6
										res["msg"] = "保存记录失败"
									} else {
										res["code"] = 0
										res["msg"] = "OK"
									}
								}
							}
						}
					}
				}
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
